import React, { useState, useEffect } from 'react';
import { 
  View, 
  Text, 
  FlatList, 
  RefreshControl, 
  Alert, 
  SafeAreaView,
  StatusBar 
} from 'react-native';
import { useRouter } from 'expo-router';
import PostCard from '../components/PostCard';
import LoadingState from '../components/LoadingState';
import EmptyState from '../components/EmptyState';
import { PostData } from '../../types/post';
import { getHomePosts, toggleLikePost, toggleFavoritePost } from '../services/postService';

/**
 * 首页帖子列表组件 - 校园社交应用首页
 * 展示所有用户发布的帖子，支持刷新和加载更多
 */
const HomePostListScreen: React.FC = () => {
  const router = useRouter();
  const [posts, setPosts] = useState<PostData[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const pageSize = 10;

  // 加载首页帖子
  const loadPosts = async (reset = false) => {
    if (loading) return;
    if (!reset && !hasMore) return;
    try {
      if (reset) {
        setInitialLoading(true);
        setPage(1);
      } else {
        setLoading(true);
      }
      const res = await getHomePosts({ current: reset ? 1 : page, pageSize });
      if (res.code === 0) {
        const newPosts = res.data.records.map((item: any) => ({
          ...item,
          title: item.title,
          user: {
            id: item.user?.id,
            name: item.user?.nickname || '',
            nickname: item.user?.nickname || '',
            avatar: item.user?.userAvatar || 'https://qqhe-1326939213.cos.ap-beijing.myqcloud.com/user_avatar/1/AbXrLsig-avatar.png',
            college: item.user?.college || '',
            major: item.user?.major || '',
            grade: item.user?.grade || '',
          },
          content: item.summary || (item.content?.length > 200 ? item.content.slice(0, 200) + '...' : item.content),
          tags: item.tags || [],
          images: item.images || [],
          createTime: item.createTime,
          updateTime: item.updateTime,
          stats: {
            likes: item.thumbNum || 0,
            comments: item.commentNum || 0,
            shares: 0,
            favourites: item.favourNum || 0,
          },
          isLiked: item.hasThumb || false,
          isFavorited: item.hasFavour || false,
        }));
        setPosts(reset ? newPosts : [...posts, ...newPosts]);
        setHasMore(res.data.current < res.data.pages);
        setPage(reset ? 2 : page + 1);
      } else {
        Alert.alert('加载失败', res.message || '获取帖子失败');
      }
    } catch (e) {
      Alert.alert('网络错误', '无法获取帖子数据');
    } finally {
      setInitialLoading(false);
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    loadPosts(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 下拉刷新
  const handleRefresh = () => {
    setRefreshing(true);
    loadPosts(true);
  };

  // 加载更多
  const handleLoadMore = () => {
    if (!loading && hasMore) {
      loadPosts();
    }
  };

  // 点击帖子跳转到详情页
  const handlePostPress = (postId: number) => {
    router.push(`/post/${postId}`);
  };

  // 点赞
  const handleLike = async (postId: number) => {
    try {
      await toggleLikePost(postId);
      setPosts(posts => posts.map(post => post.id === postId ? { ...post, isLiked: !post.isLiked, stats: { ...post.stats, likes: post.isLiked ? post.stats.likes - 1 : post.stats.likes + 1 } } : post));
    } catch {
      Alert.alert('操作失败', '请登录后再试');
    }
  };

  // 收藏
  const handleFavorite = async (postId: number) => {
    try {
      await toggleFavoritePost(postId);
      setPosts(posts => posts.map(post => post.id === postId ? { ...post, isFavorited: !post.isFavorited, stats: { ...post.stats, favourites: post.isFavorited ? post.stats.favourites - 1 : post.stats.favourites + 1 } } : post));
    } catch {
      Alert.alert('操作失败', '请登录后再试');
    }
  };

  // 评论、分享、用户点击等未开发功能
  const handleComment = () => {
    Alert.alert('功能开发中', '评论功能正在开发中，敬请期待！');
  };
  const handleShare = () => {
    Alert.alert('功能开发中', '分享功能正在开发中，敬请期待！');
  };
  const handleUserPress = () => {
    Alert.alert('功能开发中', '个人主页功能正在开发中，敬请期待！');
  };

  // 渲染帖子项
  const renderPostItem = ({ item }: { item: PostData }) => (
    <PostCard
      post={item}
      onPostPress={handlePostPress}
      onLike={handleLike}
      onComment={handleComment}
      onFavorite={handleFavorite}
      onShare={handleShare}
      onUserPress={handleUserPress}
    />
  );

  // 渲染加载更多指示器
  const renderFooter = () => {
    if (!loading) return null;
    return (
      <View className="py-4 items-center">
        <Text className="text-gray-500">正在加载更多...</Text>
      </View>
    );
  };

  // 如果是初始加载状态，显示加载组件
  if (initialLoading) {
    return (
      <SafeAreaView className="flex-1 bg-gray-50">
        <StatusBar barStyle="dark-content" backgroundColor="#F9FAFB" />
        <LoadingState message="正在加载校园动态..." />
      </SafeAreaView>
    );
  }
  
  return (
    <SafeAreaView className="flex-1 bg-gray-50">
      <StatusBar barStyle="dark-content" backgroundColor="#F9FAFB" />

      {/* 帖子列表 */}
      <FlatList
        data={posts}
        renderItem={renderPostItem}
        keyExtractor={(item) => item.id.toString()}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={handleRefresh}
            colors={['#3B82F6']}
            tintColor="#3B82F6"
          />
        }
        onEndReached={handleLoadMore}
        onEndReachedThreshold={0.1}
        ListFooterComponent={renderFooter}
        ListEmptyComponent={
          <EmptyState 
            title="暂无动态"
            message="还没有任何校园动态，快来发布第一个吧！"
            icon="chatbubbles-outline"
          />
        }
        contentContainerStyle={{ 
          paddingBottom: 20,
          flexGrow: 1 
        }}
      />
    </SafeAreaView>
  );
};

export default HomePostListScreen;
